import { Form, Input, Flex, Space, Button, Table, Select } from "antd";
import { forwardRef, useImperativeHandle, useMemo, useState } from "react";
import styled from "styled-components";
import { dataSubjectDesign } from '@/api/sharing/dataSubject'
import { useDictOptions } from "@/hooks";

const InputForm = forwardRef(({ style, subjectDetail }, ref) => {
  const { data: paramTypeOptions } = useDictOptions(['param_type'])
  const [form] = Form.useForm()
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  useImperativeHandle(ref, () => ({
    validateFields: form.validateFields,
    submit: () => {
      const values = form.getFieldsValue()
      values.paramList = values.themeParamDtos
      delete values.paramList;
      return dataSubjectDesign(values)
    },
    getFieldsValue: form.getFieldsValue
  }))

  const columns = [
    {
      title: '参数名称',
      dataIndex: 'paramName',
      render: (text, record, index) => {
        return <Form.Item
          name={['paramList', index, 'paramName']}
          rules={[
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value && getFieldValue(['paramList', index, 'paramType'])) {
                  return Promise.reject(new Error('请填写名称'));
                }
                return Promise.resolve();
              },
            })
          ]}>
          <Input
            placeholder="请填写参数名称"
          />
        </Form.Item>
      }
    },
    {
      title: '参数类型',
      dataIndex: 'paramType',
      width: 200,
      render: (text, record, index) => {
        return <Form.Item
          name={['paramList', index, 'paramType']}
          rules={[
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value && getFieldValue(['paramList', index, 'paramName'])) {
                  return Promise.reject(new Error('请选择'));
                }
                return Promise.resolve();
              },
            }),
          ]}>
          <Select placeholder='请选择参数类型' options={paramTypeOptions}></Select>
        </Form.Item>
      }
    },
    {
      title: '参数说明',
      dataIndex: 'paramRemark',
      render: (text, record, index) => {
        return <Form.Item name={['paramList', index, 'paramRemark']}>
          <Input
            placeholder="请填写参数说明"
          />
        </Form.Item>
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          <a onClick={() => tableDelete(record)}>删除</a>
        </>
      ),
    }
  ]
  const tableAdd = () => {
    let data = form.getFieldValue('paramList') || []
    form.setFieldValue('paramList', [{ rowId: new Date().getTime(), paramName: '', paramType: '', paramRemark: '', themeId: subjectDetail.id }, ...data])
  }

  const tableDelete = (record) => {
    let ids = record ? [record.rowId] : selectedRowKeys
    let data = form.getFieldValue('paramList') || []
    form.setFieldValue('paramList', data.filter(item => !ids.includes(item.rowId)))
  }

  const onSelectChange = (selectedRowKeys) => {
    setSelectedRowKeys(selectedRowKeys)
  }

  return <StyleWrapper>
    <Form style={style} layout="horizontal" form={form} initialValues={{ ...subjectDetail, paramList: (subjectDetail.paramList || []).map(d => ({ ...d, rowId: d.id })) }}>
      <Form.Item name="themeName" label="主题名称">
        <Input
          disabled
          placeholder="请填写主题名称"
        />
      </Form.Item>
      <Form.Item name="accessUrl" label="访问地址">
        <Input
          disabled
          placeholder="请填写访问地址"
        />
      </Form.Item>

      <Form.Item
        name="themeRemark"
        label="主题描述"
      >
        <Input.TextArea
          rows={2}
          disabled
          placeholder="请输入内容"
        />
      </Form.Item>
      <div className="table-wrapper">
        <Flex className="table-header" justify={'space-between'} align={'center'} >
          <span className="title">参数设计</span>
          <Space>
            <Button type="primary" onClick={tableAdd}>添加</Button>
            {!!selectedRowKeys.length && <Button danger onClick={() => {
              tableDelete()
            }}>删除</Button>}
          </Space>
        </Flex>
        <Form.Item name={'paramList'} valuePropName="dataSource">
          <Table
            rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
            rowKey="rowId"
            size="small"
            columns={columns}
            pagination={false}
            bordered
          />
        </Form.Item>
      </div>
    </Form>
  </StyleWrapper>
})

const StyleWrapper = styled.div`
.ant-form {
  max-width: 840px;
  margin: 0 auto;
}
  .table-wrapper{
    .table-header{
      margin-bottom: 20px;
      .title{
        font-size: 16px;
        font-weight: bold;
      }
    }
    .ant-table .ant-form-item {
      margin-bottom: 0;
    }
    .ant-table .ant-table-tbody .ant-table-cell{
      padding: 0;
    }

    .ant-table .ant-form-item-additional{
      position: absolute;
    }
  }
  
`

export default InputForm